package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.eduservice.entity.EduChapter;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.entity.chapter.ChapterVo;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author ZhanK
 * @since 2022-02-20
 */
@Api(description = "章节管理")
@RestController
@CrossOrigin
@RequestMapping("/eduservice/chapter")
public class EduChapterController {
    @Autowired
    EduChapterService eduChapterService;
    @Autowired
    EduVideoService eduVideoService;

    //课程大纲列表，根据课程ID进行查询出所有的章节，章节里面封装所属所有小节
    @GetMapping(value = ("getChapterVideo/{courseId}"))
    public R getChapterVo(@PathVariable String courseId){

           List<ChapterVo> list = eduChapterService.getChapterVoByCourseId(courseId);

           return R.ok().data("list",list);
    }

    //添加章节
    @PostMapping(value = ("addChapter"))
    public R addChapter( @RequestBody EduChapter eduChapter){
        boolean save = eduChapterService.save(eduChapter);
         if (save){
             return R.ok();
         }
          return R.error();
    }
    //根据章节id查询
    @GetMapping(value = ("getChapterInfo/{chapterId}"))
    public R getChapterInfo(@PathVariable String chapterId){
        EduChapter eduChapter = eduChapterService.getById(chapterId);
        return R.ok().data("chapter",eduChapter);
    }
    //修改章节
    @PostMapping(value = ("updateChapter"))
    public R updateChapter(@RequestBody EduChapter eduChapter){
        boolean b = eduChapterService.updateById(eduChapter);
        return R.ok();
    }
    //删除章节
    @DeleteMapping(value = ("deleteChapter/{chapterId}"))
    public R deleteChapter( @PathVariable String chapterId){
        QueryWrapper<EduVideo> eduVideoQueryWrapper = new QueryWrapper<>();
        eduVideoQueryWrapper.eq("chapter_id", chapterId);
        int count = eduVideoService.count(eduVideoQueryWrapper);
        if (count>0){
            throw new GuliException(20001,"该章节下面存在"+count+"个小节，清先删除");
        }
        boolean b = eduChapterService.removeById(chapterId);  //这个mybatisPlus返回值无论找没找到都返回ture。在basemapper里面用delete返回的是int。。。。
        if (b){
            return R.ok();
        } else
            return R.error();


    }


}

